<?php

namespace api\models;

use Yii;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "{{%admin_user}}".
 *
 * @property integer $user_id
 * @property string  $username
 * @property string  $password
 * @property string  $mobile_phone
 * @property string  $last_ip
 * @property string  $last_time
 * @property string  $permission_name
 */
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    public $password_repeat;

    /**
     * @inheritdoc
     */
    public static function tableName ()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules ()
    {
        return [
            [ [ 'username' ,  'leader', 'password', 'type' ] , 'required' ] ,
            [ [ 'is_pc' ,'is_mobile',  'is_audit', 'is_check_project', 'is_edit_project','is_edit_notice','is_create_account' ] , 'required' ] ,

            [ [ 'username' ] , 'string' , 'max' => 10 ] ,
            [ [ 'password' ] , 'string' , 'min' => 6 ] ,

//            [
//                'password_repeat' ,
//                'compare' ,
//                'compareAttribute' => 'password' ,
//                'message'          => '两次密码不一致' ,
//                'skipOnEmpty'      => FALSE ,
//            ] ,
            [ [ 'username' ] , 'unique' , 'message' => '该用户已存在' ] ,
            [ [ 'project_name' ] , 'unique' , 'message' => '该项目已存在' ] ,
            [
                'mobile_phone' ,
                'match' ,
                'pattern' => '#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#' ,
                'message' => '请输入正确的手机号码' ,
            ] ,
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels ()
    {
        return [
            'id'                 => 'User ID' ,
            'nickname'           => '角色类型' ,
            'username'           => '账号' ,
            'project_name'       => '项目名称' ,
            'leader'             => '负责人' ,
            'type'               => '人员类型' ,
            'password'           => '密码' ,
            'mobile_phone'       => '手机号' ,
            'last_ip'            => '上一次登录IP' ,
            'last_time'          => '上一次登录时间' ,
            'is_pc'              => '能否登录PC端' ,
            'is_mobile'          => '能否登录移动端' ,
            'is_audit'           => '能否审核' ,
            'is_check_project'   => '能否查看物资' ,
            'is_edit_project'    => '能否修改物资' ,
            'is_edit_notice'     => '能否发布公告' ,
            'is_create_account'  => '能否创建账号' ,
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity ( $id )
    {
        return static::findOne( [ 'id' => $id ] );
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken ( $token , $type = NULL )
    {
        //throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
        return static::findOne( [ 'access_token' => $token ] );
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     *
     * @return static|null
     */
    public static function findByPasswordResetToken ( $token )
    {
        if ( !static::isPasswordResetTokenValid( $token ) ) {
            return NULL;
        }

        return static::findOne( [
            'password_reset_token' => $token ,
            'status'               => self::STATUS_ACTIVE ,
        ] );
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     *
     * @return bool
     */
    public static function isPasswordResetTokenValid ( $token )
    {
        if ( empty( $token ) ) {
            return FALSE;
        }

        $timestamp = (int)substr( $token , strrpos( $token , '_' ) + 1 );
        $expire = Yii::$app->params[ 'user.passwordResetTokenExpire' ];

        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId ()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey ()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey ( $authKey )
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     *
     * @return bool if password provided is valid for current user
     */
    public function validatePassword ( $password )
    {
        return Yii::$app->security->validatePassword( $password , $this->password );
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword ( $password )
    {
        $this->password = Yii::$app->security->generatePasswordHash( $password );
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey ()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken ()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken ()
    {
        $this->password_reset_token = NULL;
    }

    /**
     * Finds user by username
     *
     * @param string $username
     *
     * @return static|null
     */
    public static function findByUserName ( $username )
    {
        return static::findOne( [ 'username' => $username ] );
    }
}
